<?php
class CommonAction extends Action {
		function _initialize() {
		// 用户权限检查
		if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
			import ( '@.ORG.RBAC' );
			if (! RBAC::AccessDecision ()) {
				//检查认证识别号
				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
					//跳转到认证网关
					redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
				}
				// 没有权限 抛出错误
				if (C ( 'RBAC_ERROR_PAGE' )) {
					// 定义权限错误页面
					redirect ( C ( 'RBAC_ERROR_PAGE' ) );
				}/* else {
					if (C ( 'GUEST_AUTH_ON' )) {
						$this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
					}
					// 提示错误信息
					$this->error ( L ( '_VALID_ACCESS_' ) );
				}*/
			}
		}
    }

    /*+------------------------------------------
      |    获取功能下拉选择框tree
      +------------------------------------------
      |    @param id 默认处于选中状态的一项
      +------------------------------------------
     */
    public function getFunctionTree($id) {
        $t_function = D("function"); 
        $result= $t_function ->field("id,pid,function_title,path") -> order("path asc")->select();
        foreach($result as $row){
            if($id){
                if($row['id'] == $id){
                        $str   .= "<option selected value=\"{$row['id']}\">";
                }else{
                        $str   .= "<option value=\"{$row['id']}\">";
                }
            }else{
                  $str   .= "<option id='{$row['id']}' value=\"{$row['id']}\">";
            }
            $count = count(explode(",",$row['path']))-1;
            $str  .= str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;|",$count);
            $str  .= "--".$row['function_title'];
            $str  .= "</option>";
        }
        return $str;
    }

    /*+---------------------------------------------------------
	  |     获取功能有序列表
	  +---------------------------------------------------------
	  |     @param => pid =>某级分类的父ID
      +---------------------------------------------------------
      |     @param => addition['before'] -> 插入到<a>之前
      |               addition['after']  -> 插入到</a>之后
      +---------------------------------------------------------
	  */
    public function get_menu($pid,$addition = array("before"=>"","after"=>"","link"=>"1")){
	    $pos=D("function");
		$show_list=$pos->where("pid = {$pid}")->select();
		$pro_menu="<ul>";
		$pro_menu.=$this->digui($show_list,$addition);   //无限分类，递归调用
		$pro_menu.="</ul>";	
		return $pro_menu;
	}
    
	/*+---------------------------------------------------------————————————————————————————————————————————————————————————————————————————————————————
	  |     递归调用，判断是否还有子类别，将所有子类别，查询出来
	  +---------------------------------------------------------————————————————————————————————————————————————————————————————————————————————————————
	  |     @param => list => 当前级分类的查询结果
	  +---------------------------------------------------------————————————————————————————————————————————————————————————————————————————————————————
	  |     @param => addition 附加的内容，如表单，复选框，连接等等
	  +—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
	  |      特殊说明 => addition参数 :
	  |               第一种：
	  |               $param = array(
	  | 				          'before' => array(    //追加在字符串的前面，before换成after可追加到字符串的后面,且结构相同
	  |								  'content'=>'&nbsp;<input type="checkbox" CK name="id[]" value="PK"/>&nbsp;&nbsp;',     //追加的字符串
	  |								  'explode'=>array(            //将字符串中的某字符替换成某字符
	  |												   '0'=>array(             //第一种替换成字符串时,使用时，根据不同的PK值替换成不同的swap或field
	  |														      'PK'  =>'CK',
	  |															  'swap'=>'checked',
	  |														 ), 
	  |												   '1'=>array(             //第二种替换成值时
	  |															  'PK'  =>'PK',
	  |															  'field'=>'id',
	  |														 ),
	  |														 
	  |														 .
	  |														 .
      |														 .
	  |														 .
	  |											
      |  													  ),
	  |                               'in_array' => array,   //用于复选框中确认为默认选中状态的字符串，是一个数组，如果此下标不存在的话，所有的字符串都不为选中状态
	  |								  ),
	  |                                
	  |						     'link' =>"0"    //不显示连接，"link" => "1"时显示连接；
	                             'in_array' => array,   //存在时候，主键在在数组中则显示
	  |						     'after' => "{$string}",     //追加到字符串的后面,同before
	  |               );
	  |				第二种：
	  |				$param = array(
	  |				               'before' => "{$string}",   //默认使用PK进行替换，且替换成值
	  |							   'link'   => '0/1',
	  |							   'after'  => "{$string}",
	  |				);
	  +______________________________________________________________________________________________________________________________________________
	  */
    public function digui($list,$addition){
        //dump($addition);
		$pos=D("function");
		foreach($list as $key=>$val){
            if(isset($addition['in_array'])){
				if(in_array($val['id'],$addition['in_array'])){
            $pro_menu.="<li>";
            if(isset($addition['before'])){
				      if(is_array($addition['before'])){
						     $content = $addition['before']['content'];
							 if($addition['before']['in_array']){
							 		$in_array= $addition['before']['in_array'];
							 }
							 //echo "<pre>";
							 //print_r($addition['before']['explode']);
						     foreach($addition['before']['explode'] as $kkk => $vvv){
							          //print_r($vvv);
								      foreach($vvv as $kk => $vv){
									          //echo $kk ."=>".$vv;
										      if($kk == "swap"){
												  if(!isset($in_array)){
												           $content  = str_replace($vvv['PK'],"",$content);
												  }else{
												        if(in_array($val['id'],$in_array)){
														     
														     $content  = str_replace($vvv['PK'],$vv,$content);
														}else{
														     $content  = str_replace($vvv['PK'],"",$content);
														}
												  }
												  //echo $content;
												  //exit;
											  }
											  if($kk == "field"){
												   //echo $vv;
												   //echo $vvv['PK'];
												   $content = str_replace($vvv['PK'],$val[$vv],$content);   
											  }
									  }
							          //$ = str_replace($val['pk'],$val[]) 	 
							 }
							 $pro_menu .= $content;
						     //echo $content;
							 //exit;
					  }elseif(is_string($addition['before'])){
                            $before   = explode("PK",$addition['before']);
                            $num = count($before);
                            for($i=0;$i<$num-1;$i++){
                                 $pro_menu.= $before[$i].$val['id'];
                            }
                            $pro_menu.=$before[$num-1];
					  }else{
						    $this->error("警告：\n\t get_num()函数使用错误，参数二只能是数组或字符串！");
						  }
            }
			
            if($val['function_entry'] != "" && $addition['link'] == '1'){
                      $pro_menu.="<a target='main' href='".__ROOT__."/";
				      $pro_menu.=$val['function_entry']."/";
					  if($val['function_act'] !=""){
					  		$pro_menu.=$val['function_act']."/";
						}
					  if($val['function_app'] != ""){
				      		$pro_menu.=$val['function_app']."/";
					  }
					  if($val['id'] != ""){
				      		$pro_menu.="Fid/".$val['id']."/";
					  }
                      $pro_menu.="'>".$val["function_title"]."</a>";
                      
			}else{
                      
                      $pro_menu.=$val["function_title"];
                      
            }
            if(isset($addition['after'])){
			          if(is_array($addition['after'])){
						     $content = $addition['after']['content'];
							 //echo "<pre>";
							 //print_r($addition['before']['explode']);
							 if($addition['after']['in_array']){
							 		$in_array= $addition['after']['in_array'];
							 }
						     foreach($addition['after']['explode'] as $kkk => $vvv){
							          //print_r($vvv);
								      foreach($vvv as $kk => $vv){
									          //echo $kk ."=>".$vv;
										      if($kk == "swap"){
											      if(!isset($in_array)){
												           $content  = str_replace($vvv['PK'],"",$content);
												  }else{
												        if(in_array($val['id'],$in_array)){
														     $content  = str_replace($vvv['PK'],$vv,$content);
														}else{
														     $content  = str_replace($vvv['PK'],"",$content);
														}
												  }
												  //echo $content;
												  //exit;
											  }
											  if($kk == "field"){
												   //echo $vv;
												   //echo $vvv['PK'];
												   $content = str_replace($vvv['PK'],$val[$vv],$content);   
											  }
									  }
							          //$ = str_replace($val['pk'],$val[]) 	 
							 }
							 $pro_menu .= $content;
						     //echo $content;
							 //exit;
					   }elseif(is_string($addition['after'])){
                            $after   = explode("PK",$addition['after']);
                            $num = count($after);
                            for($i=0;$i<$num-1;$i++){
                                 $pro_menu.= $after[$i].$val['id'];
                            }
                            $pro_menu.=$after[$num-1];
					  }
            }
				}
			}else{
				
				
				
		$pro_menu.="<li>";
            if(isset($addition['before'])){
				      if(is_array($addition['before'])){
						     $content = $addition['before']['content'];
							 if($addition['before']['in_array']){
							 		$in_array= $addition['before']['in_array'];
							 }
							 //echo "<pre>";
							 //print_r($addition['before']['explode']);
						     foreach($addition['before']['explode'] as $kkk => $vvv){
							          //print_r($vvv);
								      foreach($vvv as $kk => $vv){
									          //echo $kk ."=>".$vv;
										      if($kk == "swap"){
												  if(!isset($in_array)){
												           $content  = str_replace($vvv['PK'],"",$content);
												  }else{
												        if(in_array($val['id'],$in_array)){
														     
														     $content  = str_replace($vvv['PK'],$vv,$content);
														}else{
														     $content  = str_replace($vvv['PK'],"",$content);
														}
												  }
												  //echo $content;
												  //exit;
											  }
											  if($kk == "field"){
												   //echo $vv;
												   //echo $vvv['PK'];
												   $content = str_replace($vvv['PK'],$val[$vv],$content);   
											  }
									  }
							          //$ = str_replace($val['pk'],$val[]) 	 
							 }
							 $pro_menu .= $content;
						     //echo $content;
							 //exit;
					  }elseif(is_string($addition['before'])){
                            $before   = explode("PK",$addition['before']);
                            $num = count($before);
                            for($i=0;$i<$num-1;$i++){
                                 $pro_menu.= $before[$i].$val['id'];
                            }
                            $pro_menu.=$before[$num-1];
					  }else{
						    $this->error("警告：\n\t get_num()函数使用错误，参数二只能是数组或字符串！");
						  }
            }
			
            if($val['function_entry'] != "" && $addition['link'] == '1'){
                      $pro_menu.="<a target='main' href='".__ROOT__."/";
				      $pro_menu.=$val['function_entry']."/";
					  if($val['function_act'] !=""){
					  		$pro_menu.=$val['function_act']."/";
						}
					  if($val['function_app'] != ""){
				      		$pro_menu.=$val['function_app']."/";
					  }
					  if($val['id'] != ""){
				      		$pro_menu.="Fid/".$val['id']."/";
					  }
                      $pro_menu.="'>".$val['id']." ".$val["function_title"]."</a>";
                      
			}else{
                      
                      $pro_menu.=$val['id']." ".$val["function_title"];
                      
            }
            if(isset($addition['after'])){
			          if(is_array($addition['after'])){
						     $content = $addition['after']['content'];
							 //echo "<pre>";
							 //print_r($addition['before']['explode']);
							 if($addition['after']['in_array']){
							 		$in_array= $addition['after']['in_array'];
							 }
						     foreach($addition['after']['explode'] as $kkk => $vvv){
							          //print_r($vvv);
								      foreach($vvv as $kk => $vv){
									          //echo $kk ."=>".$vv;
										      if($kk == "swap"){
											      if(!isset($in_array)){
												           $content  = str_replace($vvv['PK'],"",$content);
												  }else{
												        if(in_array($val['id'],$in_array)){
														     $content  = str_replace($vvv['PK'],$vv,$content);
														}else{
														     $content  = str_replace($vvv['PK'],"",$content);
														}
												  }
												  //echo $content;
												  //exit;
											  }
											  if($kk == "field"){
												   //echo $vv;
												   //echo $vvv['PK'];
												   $content = str_replace($vvv['PK'],$val[$vv],$content);   
											  }
									  }
							          //$ = str_replace($val['pk'],$val[]) 	 
							 }
							 $pro_menu .= $content;
						     //echo $content;
							 //exit;
					   }elseif(is_string($addition['after'])){
                            $after   = explode("PK",$addition['after']);
                            $num = count($after);
                            for($i=0;$i<$num-1;$i++){
                                 $pro_menu.= $after[$i].$val['id'];
                            }
                            $pro_menu.=$after[$num-1];
					  }
            }
				}		
				
				
				
			
			$show_list=$pos->where("pid=".$val["id"])->select();
			if(count($show_list)>0){
			       $pro_menu.="<ul>";
			       $pro_menu.=$this->digui($show_list,$addition);
			       $pro_menu.="</ul></li>";
			}else{
			       $pro_menu.="</li>";
			}
			
		}
		return $pro_menu;
	}

    /*+-------------------------------------
      |    统计数据条数，用户分页使用
      +-------------------------------------
     */
    public function countData($t_name,$where=""){
        $data  = D($t_name);
        if($where){
            $count = $data ->where($where)->count();
        }else{
            $count = $data ->count();
        }
        return $count;
    }

    /*+——————-------------
      |   获取组信息
      +-------------------------
     */
    public function getGroupInfo($query,$addition){
           $group     = new Model();
           $list   =  $group->query($query);
		   if($addition){
		          foreach($list as $key => $val){
				         if($val['Gid'] == $_GET['Gid']){
						        $list[$key]['checked'] = "checked";
						 }
				  }
		   }
		  
		   $this->assign("list",$list);
    }
	

    //分页、
    public function pageOperate($table,$num,$where){
           $count = $this->countData($table,$where);
           import("@.ORG.Page");
           $page  = new Page($count,$num);
           $pageInfo['firstRow'] = $page->firstRow;
           $pageInfo['listRows'] = $page->listRows;
           $this->assign("page",$page->show());
           return $pageInfo;
    }
	
	/*+--------------------------------------------
	  |     将数组转换成为字符串
	  +--------------------------------------------
	  */
	public function arrayToString($array){
		   if($array){
			    foreach($array as $val){
				       $in .= $val.",";	
				}
				$in = rtrim($in,",");
				return $in;
		   }else{
			    $this->error("抱歉：\n\t请传入想要转换的数组！");
	       }
    }
    
	/*+--------------------------------------------
	  |     数组重组
	  +--------------------------------------------
	  */
    public function arraySwitch($array){
		    foreach($array as $key => $val){
				 if(is_array($val)){
					    foreach($val as $k => $v){
							 $newArray[$k][$key] = $v;
							}
					 }
				}
				return $newArray;
     }
    
    /*+-----------------------------------------
      |      获取单个汉字的首字母
      +-----------------------------------------
     */ 
    public function getfirstchar($s0){     
            $fchar = ord($s0{0});  
            if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});  
            $s1 = iconv("UTF-8","gb2312", $s0);  
            $s2 = iconv("gb2312","UTF-8", $s1);  
            if($s2 == $s0){$s = $s1;}else{$s = $s0;}  
            $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;  
            if($asc >= -20319 and $asc <= -20284) return "A";  
            if($asc >= -20283 and $asc <= -19776) return "B";  
            if($asc >= -19775 and $asc <= -19219) return "C";  
            if($asc >= -19218 and $asc <= -18711) return "D";  
            if($asc >= -18710 and $asc <= -18527) return "E";  
            if($asc >= -18526 and $asc <= -18240) return "F";  
            if($asc >= -18239 and $asc <= -17923) return "G";  
            if($asc >= -17922 and $asc <= -17418) return "I";  
            if($asc >= -17417 and $asc <= -16475) return "J";  
            if($asc >= -16474 and $asc <= -16213) return "K";  
            if($asc >= -16212 and $asc <= -15641) return "L";  
            if($asc >= -15640 and $asc <= -15166) return "M";  
            if($asc >= -15165 and $asc <= -14923) return "N";  
            if($asc >= -14922 and $asc <= -14915) return "O";  
            if($asc >= -14914 and $asc <= -14631) return "P";  
            if($asc >= -14630 and $asc <= -14150) return "Q";  
            if($asc >= -14149 and $asc <= -14091) return "R";  
            if($asc >= -14090 and $asc <= -13319) return "S";  
            if($asc >= -13318 and $asc <= -12839) return "T";  
            if($asc >= -12838 and $asc <= -12557) return "W";  
            if($asc >= -12556 and $asc <= -11848) return "X";  
            if($asc >= -11847 and $asc <= -11056) return "Y";  
            if($asc >= -11055 and $asc <= -10247) return "Z";  
            return null;  
      }  
    /*+---------------------------------
      |     获取所有汉字的首字母
      +---------------------------------
     */ 
   public function pinyin($zh){  
            $ret = "";  
            $s1 = iconv("UTF-8","gb2312", $zh);  
            $s2 = iconv("gb2312","UTF-8", $s1);  
            if($s2 == $zh){$zh = $s1;}  
            for($i = 0; $i < strlen($zh); $i++){  
                    $s1 = substr($zh,$i,1);  
                    $p = ord($s1);  
                    if($p > 160){  
                            $s2 = substr($zh,$i++,2);  
                            $ret .= $this->getfirstchar($s2);  
                    }else{  
                            $ret .= $s1;  
                    }  
            }  
            return $ret;  

    }  

    /*+------------------------------------+
	  |       组织共功能插入语句              |
	  +------------------------------------+*/
    public function getFunctionInsertSQL(){
		   $func       = D("function");
		   $funcId = $this->getWebsiteFunctionId();
		   $funcInfo = $func -> where("id in ({$funcId})") ->select();
		   //print_r($funcInfo);
		   //功能的values信息
		   $funcValues ="";
		   foreach($funcInfo as $key => $val){
		          $funcValues .="(";
		          foreach($val as $k => $v){
		           		if($k != "create_time"){
						      if($k == "id" || $k == "position" || $k == "create_user"){
						           $funcValues .= $v.",";
							  }else{
							       $funcValues .= "'".$v."',";
							  }
						}else{
						      $funcValues .= "'".$v."'";
						}
				  }
				  $funcValues .="),"; 
		   }
		   $funcValues  = rtrim($funcValues,",");
		   $funcValues .= ";";
		   $updataFunction = "INSERT INTO `douhao_function` (`id`, `pid`, `path`, `function_entry`, `function_act`, `function_title`, `function_app`, `function_abstruct`, `status`, `position`, `create_user`, `create_time`) VALUES".$funcValues;
		   return $updataFunction;
	} 	
	/*+------------------------------------+
	  |       获取功能最新ID                 |
	  +------------------------------------+*/
	public function getWebsiteFunctionId(){
	        $pos=D("function");
		    $show_list=$pos->field("id")->where("pid = 136")->select();
		    return rtrim($this->diguiId($show_list),",");   //无限分类，递归调用
	}

	public function diguiId($list){
		$pos=D("function");
		foreach($list as $key=>$val){
		    $pro_menu .=$val['id'].",";
			$show_list=$pos->field("id")->where("pid = {$val['id']}")->select();
			if(count($show_list)>0){
			       $pro_menu.=$this->diguiId($show_list);
			}
			
		}
		return $pro_menu;
	}

    /*+---------------------------------------------
      |    切换数据库
      +---------------------------------------------
     */
    public function changeDB(){
           C("DB_NAME",$_SESSION[C("DATA_KEY")]);
    }

    /*+---------------------------------------------
      |    获取文件上传配置
      +---------------------------------------------*/
    public function uploadConfig($column_id){
           $config  = D("website_config");
           $info    = $config->where("column_id = {$column_id} and pid = 2")->select();
           return $info;
    }
    /*+---------------------------------------------
      |    文件上传
      +---------------------------------------------*/
    protected function _upload($config) {
        import("@.ORG.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        if($config['maxSize']){
              $upload->maxSize = $config['maxSize']*1024*1024;
        }else{
              $upload->maxSize = 3292200;
        }
        //设置上传文件类型
        if(array_key_exists('allowExtsExplode',$config) && array_key_exists('allowExts',$config)){
            $upload->allowExts = explode($config['allowExtsExplode'],$config['allowExts']);
        }else{
            $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
        }

        //设置附件上传目录
        if($config['savePath']){
            $upload->savePath = $config['savePath'];
        }else{
            $upload->savePath = '../Data/Admin/Uploads/'.date("Y")."/".date('m').'/'.date('d')."/";
        }
        //设置需要生成缩略图，仅对图像文件有效
        if($config['thumb']){
            $upload->thumb = $config['thumb'];
        }else{
            $upload->thumb = true;
        }
        // 设置引用图片类库包路径
        $upload->imageClassPath = '@.ORG.Image';
        //设置需要生成缩略图的文件后缀
        if($config['thumbPrefix']){
            $upload->thumbPrefix = $config['thumbPrefix'];
        }else{
            $upload->thumbPrefix = 's_,m_';  //生产2张缩略图
        }
        //设置缩略图最大宽度
        if($config['thumbMaxWidth']){
            $upload->thumbMaxWidth =$config['thumbMaxWidth'];
        }else{
            $upload->thumbMaxWidth = '400,100';
        }
        //设置缩略图最大高度
        if($config['thumbMaxHeight']){
            $upload->thumbMaxHeight = $config['thumbMaxHeight'];
        }else{
            $upload->thumbMaxHeight = '400,100';
        }
        //设置上传文件规则
        $upload->saveRule = uniqid;
        //设置是否使用子目录保存上传文件
        //$upload->autoSub  = true;
        //设置子目录上传方式
        //$upload->subType  = 'date';
        //设置日期格式
        //$upload->dateFormat  = 'Ymd';
        //设置子目录层数
        //$upload->hashLevel   = 3;
        //删除原图
        if($config['thumbRemoveOrigin']){
            $upload->thumbRemoveOrigin = $config['thumbMaxHeight'];
        }else{
            $upload->thumbRemoveOrigin = true;
        }
        if (!$upload->upload()) {
            //捕获上传异常
            $this->error($upload->getErrorMsg());
        } else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            //echo "<pre>";
            //print_r($uploadList);exit;
            return $uploadList;
        }
    }

    /*+----------------------------------------------------------
      |       垃圾回收
      +----------------------------------------------------------
      |       在删除和修改数据的时候，将废弃的图片或附件删除
      +----------------------------------------------------------*/
    public function trashRecycling($resoure){
           $this  ->changeDB();
           $table = D($resoure['tableName']);
           $result=$table->field($resoure['field'])->where("id = {$resoure['id']}")->find(); 
           //echo "<pre>";
           //print_r($resoure);
           //echo $resoure['prefix'].$result[$resoure['field']];//exit;
          // echo "<br/>";echo ;
           return unlink($_SERVER['DOCUMENT_ROOT'].$resoure['prefix'].$result[$resoure['field']]);
    }
    //============================================||=====================================================//
    //                                            \/
    /*+---------------------------------------------
	  |    功能过滤
	  +---------------------------------------------
	  */
	public function filterFunction($Fids){
	       $in = array_intersect($Fids,$_SESSION[C('FUNCTION_KEY')]);
		   echo "<pre>";
		   print_r($in);
	}
	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
	}
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
		$name=$this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				$map [$val] = $_REQUEST [$val];
			}
		}
		return $map;

	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (isset ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( 'id' );
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			} else {
				$listRows = '';
			}
			$p = new Page ( $count, $listRows );
			//分页查询数据

			$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
			//echo $model->getlastsql();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

	function insert() {
		//B('FilterString');
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success ('新增成功!');
		} else {
			//失败提示
			$this->error ('新增失败!');
		}
	}

	public function add() {
		$this->display ();
	}

	function read() {
		$this->edit ();
	}

	function edit() {
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}

	function update() {
		//B('FilterString');
		$name=$this->getActionName();
		$model = D ( $name );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		// 更新数据
		$list=$model->save ();
		if (false !== $list) {
			//成功提示
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success ('编辑成功!');
		} else {
			//错误提示
			$this->error ('编辑失败!');
		}
	}
	/**
     +----------------------------------------------------------
	 * 默认删除操作
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	public function delete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = M ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				$list=$model->where ( $condition )->setField ( 'status', - 1 );
				if ($list!==false) {
					$this->success ('删除成功！' );
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
	}
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					//echo $model->getlastsql();
					$this->success ('删除成功！');
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
		$this->forward ();
	}

	public function clear() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			if (false !== $model->where ( 'status=1' )->delete ()) {
				$this->assign ( "jumpUrl", $this->getReturnUrl () );
				$this->success ( L ( '_DELETE_SUCCESS_' ) );
			} else {
				$this->error ( L ( '_DELETE_FAIL_' ) );
			}
		}
		$this->forward ();
	}
	/**
     +----------------------------------------------------------
	 * 默认禁用操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	public function forbid() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		$list=$model->forbid ( $condition );
		if ($list!==false) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态禁用成功' );
		} else {
			$this->error  (  '状态禁用失败！' );
		}
	}
	public function checkPass() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->checkPass( $condition )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态批准成功！' );
		} else {
			$this->error  (  '状态批准失败！' );
		}
	}

	public function recycle() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->recycle ( $condition )) {

			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态还原成功！' );

		} else {
			$this->error   (  '状态还原失败！' );
		}
	}

	public function recycleBin() {
		$map = $this->_search ();
		$map ['status'] = - 1;
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
	}

	/**
     +----------------------------------------------------------
	 * 默认恢复操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	function resume() {
		//恢复指定记录
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->resume ( $condition )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态恢复成功！' );
		} else {
			$this->error ( '状态恢复失败！' );
		}
	}


function saveSort() {
		$seqNoList = $_POST ['seqNoList'];
		if (! empty ( $seqNoList )) {
			//更新数据对象
		$name=$this->getActionName();
		$model = D ($name);
			$col = explode ( ',', $seqNoList );
			//启动事务
			$model->startTrans ();
			foreach ( $col as $val ) {
				$val = explode ( ':', $val );
				$model->id = $val [0];
				$model->sort = $val [1];
				$result = $model->save ();
				if (! $result) {
					break;
				}
			}
			//提交事务
			$model->commit ();
			if ($result!==false) {
				//采用普通方式跳转刷新页面
				$this->success ( '更新成功' );
			} else {
				$this->error ( $model->getError () );
			}
		}
	}
}
?>
